<?php

$LIB = dirname(__FILE__);

require_once($LIB. "/vendor/autoload.php");
use Overtrue\Pinyin\Pinyin;

$options = getopt("f:", ['from:', "end:"]);

$xml_file = $options['f'] ?? "";
$from_year = $options['from'] ?? 0;
$end_year = $options['end'] ?? date("Y");
if (empty($xml_file)) {
    exit("usage: php $argv[0] -f xml_file --from 2020 [--end 2022] ");
}
info("xml_file:${xml_file}, from_year:${from_year}, end_year:${end_year}");

run($xml_file, $from_year, $end_year);

function run($xml_file, $from_year, $end_year){
	$file = $xml_file;
	$html = file_get_contents($file);

	
	$pinyin = new Pinyin(); // 默认

	preg_match_all('/<item><title>(.*)<\/title>.*<link>(.*)<\/link>.*<pubDate>(.*)<\/pubDate>.*<description>(.*)<\/description><\/item>/sU', $html, $data, PREG_SET_ORDER );

	// var_dump($data);

	foreach($data as $item){
		// var_dump($item);exit;

		// 文章正文
		$content = str_replace(']]>', '', str_replace('<![CDATA[', '', $item[4]));

		// 过滤非法字符
		$title = preg_replace('/(\/|\\|\:|\*|\?|\"|\<|\>|\|)/', "", $item[1]);

		// 时间
		$datetime = date('Y-m-d H:i:s', strtotime($item[3]));

		//内容合成
        // $content = sprintf("# %s\r\n\r\n@date:%s\r\n\r\n%s", $item[1], $datetime, $content);
        $content = sprintf("# %s\n\n---\ntitle: %s\ndate: %s\n---\n\n%s",$title ,$title, $datetime, $content);


        $file_year = date('Y', strtotime($item[3]));
        if ($file_year > $end_year) {
            warn("ignore file:{$title}, file_year: ${file_year}");
            continue;
        }
        if ($file_year < $from_year) {
            warn("ignore file:{$title}, file_year: ${file_year}");
            continue;
        }
		
		$dir = 'docs/'. $file_year;

		//转成拼音，防止文件无法创建
		$filename = sprintf('%s/%s-%s.md', $dir, date('Y-m-d', strtotime($item[3])) , $pinyin->permalink($title));
		// $filename = sprintf('%s/%s-%s.md', $dir, date('Y-m-d', strtotime($item[3])) , iconv('utf-8', 'GB2312', $title));

		@mkdir($dir, 0777, true);
		@chmod($filename, 0777);
		
		$content = matchPic($content, $datetime);
		$content = matchPicMD($content, $datetime);
		
		file_put_contents($filename, $content);
		// exit;
	}
}

function matchPic($content, $datetime){
	preg_match_all('/<img src="(.*)" alt=.*>/sU', $content, $pics, PREG_SET_ORDER );
	foreach($pics as $pic){
		$url = $pic[1];
		$path_parts  =  pathinfo($url);
		$extension = @$path_parts['extension'] ? : 'jpg';
 
		if(!preg_match('/^http/', $url)){
			$url = 'http:'.$url;
		}
		
		print_r($url."  ok\n");
		
		if(checkHttpStatus($url)){
			$img_url = downPic2($url, $datetime, $extension);
			$content = str_replace($url, $img_url, $content);
		}	
	}
	
	return $content;
}

function matchPicMD($content, $datetime){
	preg_match_all('/!\[\]\((.*)\)/sU', $content, $pics, PREG_SET_ORDER );
	foreach($pics as $pic){
		//print_r($pic);
		$url = $pic[1];
		$path_parts  =  pathinfo($url);
		$extension = @$path_parts['extension'] ? : 'jpg';
 
		if(!preg_match('/^http/', $url)){
			$url = 'http:'.$url;
		}
		
		print_r($url."  ok\n");
		
		if(checkHttpStatus($url)){
            $img_url = downPic2($url, $datetime, $extension);
            $content = str_replace($url, $img_url, $content);
		}	
	}
	
	return $content;
}

function downPic2($url, $datetime, $extension){
	$extension = $extension ? : 'jpg';
	$stream_opts = [
		"ssl" => [
			"verify_peer"=>false,
			"verify_peer_name"=>false,
		]
	]; 
    $content = file_get_contents($url,false, stream_context_create($stream_opts));
    
	$dir = 'docs/images/';
	
    // $filename = $dir.date('Ymd', strtotime($datetime)).uniqid().".".$extension;
    $filename = $dir . md5($url).".".$extension; //图片文件名称
	
	@mkdir($dir, 0777, true);
	
	file_put_contents($filename, $content);
	return str_replace('docs','..',$filename);
}

